package dao;

import model.FileContent;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedList;

/**
 * PackageName: dao
 * ClassName: FileContentDao
 * Author: tum0r
 * Time: 2020/5/24 18:25
 */
public class FileContentDao extends BaseDao {

    public String check(FileContent fileContent) throws SQLException {
        String result = fileContent.getUUID();
        LinkedList<LinkedList<Object>> temp = query("SELECT UUID FROM file_content WHERE Fingerprint = ?", fileContent.getFingerprint());
        if (temp.size() == 1) {
            result = (String) temp.get(0).get(0);
        }
        return result;
    }

    public String add(FileContent fileContent) throws SQLException {
        String result = check(fileContent);
        if (result.equals(fileContent.getUUID())) {
            update("INSERT INTO file_content VALUES(?, ?, ?)", fileContent.getUUID(), fileContent.getData(), fileContent.getFingerprint());
        }
        return result;
    }

    private FileContent getFileContent(LinkedList<LinkedList<Object>> temp) {
        FileContent result = null;
        if (temp != null && temp.size() == 1) {
            LinkedList<Object> item = temp.get(0);
            result = new FileContent();
            result.setUUID((String) item.get(0));
            result.setData((byte[]) item.get(1));
            result.setFingerprint((String) item.get(2));
        }
        return result;
    }

    public LinkedList<FileContent> getFileContentByID(String[] UUID) throws SQLException {
        LinkedList<FileContent> result = new LinkedList<>();
        if (UUID != null && UUID.length != 0) {
            for (int i = 0; i < UUID.length; i++) {
                FileContent item = getFileContent(query("SELECT * FROM file_content WHERE UUID = ?", UUID[i]));
                if (item != null) {
                    result.add(item);
                }
            }
        }
        return result;
    }

}
